import * as vscode from 'vscode';
import { ErrorAnalyzer } from './errorAnalyzer';
import { LanguageManager } from './languageManager';
import {registerCommands as registerLLMCommands} from './llmAnalysisFunctions'
// 增强的LSP错误检查工具类
class LSPErrorChecker {
  /**
   * 主动获取并检查LSP错误信息
   * @param uri 文档URI
   * @returns 错误检查结果
   */
  public static async checkLSPErrors(uri: vscode.Uri): Promise<{
    hasErrors: boolean;
    details: {
      count: number;
      errors: vscode.Diagnostic[];
      summary: string;
      errorsByLine: Map<number, vscode.Diagnostic[]>;
    }
  }> {
    // 主动触发LSP诊断更新（如果需要）
    await vscode.commands.executeCommand('vscode.executeDocumentSymbolProvider', uri);
    
    // 获取最新的诊断信息
    const diagnostics = vscode.languages.getDiagnostics(uri);
    
    const errorCount = diagnostics.filter(d => d.severity === vscode.DiagnosticSeverity.Error).length;
    const warningCount = diagnostics.filter(d => d.severity === vscode.DiagnosticSeverity.Warning).length;
    const infoCount = diagnostics.filter(d => d.severity === vscode.DiagnosticSeverity.Information).length;
    
    // 按行号分组错误
    const errorsByLine = new Map<number, vscode.Diagnostic[]>();
    diagnostics.forEach(diagnostic => {
      const line = diagnostic.range.start.line;
      if (!errorsByLine.has(line)) {
        errorsByLine.set(line, []);
      }
      errorsByLine.get(line)!.push(diagnostic);
    });
    
    let summary = '';
    if (errorCount > 0) {
      summary += `${errorCount}个错误`;
    }
    if (warningCount > 0) {
      if (summary) summary += ', ';
      summary += `${warningCount}个警告`;
    }
    if (infoCount > 0) {
      if (summary) summary += ', ';
      summary += `${infoCount}个信息`;
    }
    
    return {
      hasErrors: diagnostics.length > 0,
      details: {
        count: diagnostics.length,
        errors: diagnostics,
        summary: summary || '无问题',
        errorsByLine
      }
    };
  }

  /**
   * 检查指定位置附近是否有LSP错误
   * @param uri 文档URI
   * @param position 当前位置
   * @param lineRange 检查范围（行数）
   */
  public static async checkErrorsNearPosition(
    uri: vscode.Uri, 
    position: vscode.Position, 
    lineRange: number = 3
  ): Promise<{
    hasNearbyErrors: boolean;
    nearbyErrors: vscode.Diagnostic[];
    affectedLines: number[];
  }> {
    const errorCheck = await this.checkLSPErrors(uri);
    
    const nearbyErrors: vscode.Diagnostic[] = [];
    const affectedLines: number[] = [];
    
    errorCheck.details.errors.forEach(diagnostic => {
      const errorLine = diagnostic.range.start.line;
      const distance = Math.abs(errorLine - position.line);
      
      if (distance <= lineRange) {
        nearbyErrors.push(diagnostic);
        if (!affectedLines.includes(errorLine)) {
          affectedLines.push(errorLine);
        }
      }
    });
    
    return {
      hasNearbyErrors: nearbyErrors.length > 0,
      nearbyErrors,
      affectedLines: affectedLines.sort((a, b) => a - b)
    };
  }

  /**
   * 等待LSP诊断稳定（避免分析过程中的临时错误）
   * @param uri 文档URI
   * @param maxWaitTime 最大等待时间（毫秒）
   */
  public static async waitForStableDiagnostics(uri: vscode.Uri, maxWaitTime: number = 3000): Promise<boolean> {
    let lastDiagnosticsCount = -1;
    let stableCount = 0;
    const checkInterval = 200;
    const requiredStableChecks = 3; // 需要连续3次检查结果相同才认为稳定
    
    return new Promise((resolve) => {
      const startTime = Date.now();
      
      const checkStability = () => {
        const currentDiagnostics = vscode.languages.getDiagnostics(uri);
        const currentCount = currentDiagnostics.length;
        
        if (currentCount === lastDiagnosticsCount) {
          stableCount++;
          if (stableCount >= requiredStableChecks) {
            resolve(true);
            return;
          }
        } else {
          stableCount = 0;
          lastDiagnosticsCount = currentCount;
        }
        
        if (Date.now() - startTime >= maxWaitTime) {
          console.log(`LSP诊断等待超时，当前诊断数量: ${currentCount}`);
          resolve(false);
          return;
        }
        
        setTimeout(checkStability, checkInterval);
      };
      
      checkStability();
    });
  }
}

// 修复后的防抖状态管理
class ContextAnalyzeDebouncer {
  private timeouts = new Map<string, NodeJS.Timeout>();
  private lastAnalyzed = new Map<string, { uri: string; line: number; character: number; timestamp: number }>();
  private analysisCache = new Map<string, { timestamp: number; result: any }>();

  public debounce(uri: vscode.Uri, position: vscode.Position, callback: () => Promise<void>, delay: number = 1000) {
    const fileKey = uri.toString();
    const positionKey = `${uri.toString()}-${position.line}-${position.character}`;
    
    // 检查是否是相同位置的重复调用（在短时间内）
    const lastPos = this.lastAnalyzed.get(positionKey);
    const now = Date.now();
    
    if (lastPos && now - lastPos.timestamp < 2000) { // 2秒内的重复位置跳过
      console.log(`跳过重复分析: ${position.line}:${position.character}`);
      return;
    }

    // 清除该文件的之前定时器（允许不同位置的新分析）
    if (this.timeouts.has(fileKey)) {
      clearTimeout(this.timeouts.get(fileKey)!);
    }

    // 设置新的定时器
    const timeout = setTimeout(async () => {
      console.log(`开始分析位置: ${position.line}:${position.character}`);
      
      // 记录分析位置和时间
      this.lastAnalyzed.set(positionKey, {
        uri: uri.toString(),
        line: position.line,
        character: position.character,
        timestamp: now
      });
      
      try {
        await callback();
      } catch (error) {
        console.error('上下文分析出错:', error);
      }
      
      this.timeouts.delete(fileKey);
    }, delay);

    this.timeouts.set(fileKey, timeout);
  }

  public forceAnalyze(uri: vscode.Uri, position: vscode.Position, callback: () => Promise<void>) {
    const fileKey = uri.toString();
    const positionKey = `${uri.toString()}-${position.line}-${position.character}`;
    
    // 立即执行分析，无防抖
    console.log(`强制分析位置: ${position.line}:${position.character}`);
    
    // 清除可能存在的定时器
    if (this.timeouts.has(fileKey)) {
      clearTimeout(this.timeouts.get(fileKey)!);
      this.timeouts.delete(fileKey);
    }

    // 记录分析位置
    this.lastAnalyzed.set(positionKey, {
      uri: uri.toString(),
      line: position.line,
      character: position.character,
      timestamp: Date.now()
    });

    // 立即执行
    callback().catch(error => {
      console.error('强制上下文分析出错:', error);
    });
  }

  public clear() {
    this.timeouts.forEach(timeout => clearTimeout(timeout));
    this.timeouts.clear();
    this.lastAnalyzed.clear();
    this.analysisCache.clear();
  }

  public clearFileCache(uri: vscode.Uri) {
    const fileKey = uri.toString();
    
    // 清除该文件的定时器
    if (this.timeouts.has(fileKey)) {
      clearTimeout(this.timeouts.get(fileKey)!);
      this.timeouts.delete(fileKey);
    }

    // 清除该文件的位置缓存
    const keysToDelete: string[] = [];
    this.lastAnalyzed.forEach((value, key) => {
      if (key.startsWith(fileKey)) {
        keysToDelete.push(key);
      }
    });
    keysToDelete.forEach(key => this.lastAnalyzed.delete(key));
  }

  // 获取分析统计信息
  public getStats(): { totalPositions: number; activeTimeouts: number } {
    return {
      totalPositions: this.lastAnalyzed.size,
      activeTimeouts: this.timeouts.size
    };
  }
}

export function activate(context: vscode.ExtensionContext) {
  const languageManager = new LanguageManager();
  const errorAnalyzer = new ErrorAnalyzer(languageManager);
  const debouncer = new ContextAnalyzeDebouncer();
  registerLLMCommands(context);
  // 增强的分析函数 - 主动获取LSP错误信息
  const analyzeIfNoErrors = async (uri: vscode.Uri, position: vscode.Position, source: string = 'unknown') => {
    const document = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === uri.toString());
    if (!document || !languageManager.isSupported(document.languageId)) {
      console.log(`跳过分析: 不支持的语言 ${document?.languageId || 'unknown'}`);
      return;
    }

    try {
      // 主动获取最新的LSP错误信息
      console.log(`主动检查LSP错误状态 - 触发源: ${source}`);
      const errorCheck = await LSPErrorChecker.checkLSPErrors(uri);
      
      if (errorCheck.hasErrors) {
        console.log(`跳过上下文分析: 文件存在LSP问题 (${errorCheck.details.summary}) - 触发源: ${source}`);
        
        // 显示错误信息（可选）
        if (errorCheck.details.count > 5) {
          // 只在错误较多时显示提示
          vscode.window.showWarningMessage(
            `当前文件有 ${errorCheck.details.summary}，暂停上下文分析`,
            '查看问题'
          ).then(selection => {
            if (selection === '查看问题') {
              vscode.commands.executeCommand('workbench.actions.view.problems');
            }
          });
        }
        
        // 即使跳过上下文分析，也要处理LSP错误
        if (!errorAnalyzer.hasErrors(uri)) {
          console.log(`开始LSP错误分析 - 触发源: ${source}`);
          // 这里可能需要手动触发LSP错误分析
        }
        return;
      }

      // 检查当前位置附近是否有错误（更精细的检查）
      const nearbyCheck = await LSPErrorChecker.checkErrorsNearPosition(uri, position, 2);
      if (nearbyCheck.hasNearbyErrors) {
        console.log(`跳过上下文分析: 当前位置附近存在LSP错误 (行号: ${nearbyCheck.affectedLines.join(', ')}) - 触发源: ${source}`);
        await errorAnalyzer.analyzeCurrentContext(uri, position);
        return;
      }

      // 等待LSP诊断稳定（可选，避免分析过程中的临时错误）
      const isStable = await LSPErrorChecker.waitForStableDiagnostics(uri, 1000);
      if (!isStable) {
        console.log(`LSP诊断未稳定，延迟分析 - 触发源: ${source}`);
        // 可以选择延迟重试或跳过本次分析
        setTimeout(() => {
          debouncer.debounce(uri, position, async () => {
            await analyzeIfNoErrors(uri, position, `${source}-重试`);
          }, 500);
        }, 1000);
        return;
      }

      // 最终确认：再次检查是否有新的错误
      const finalCheck = await LSPErrorChecker.checkLSPErrors(uri);
      if (finalCheck.hasErrors) {
        console.log(`最终检查发现新错误，取消分析 - 触发源: ${source}`);
        return;
      }

      // 只有在完全没有错误的情况下才进行上下文分析
      console.log(`✅ 开始上下文分析: 文件无LSP问题 - 触发源: ${source}, 位置: ${position.line}:${position.character}`);
      await errorAnalyzer.analyzeCurrentContext(uri, position);
      
    } catch (error) {
      console.error(`LSP错误检查失败 - 触发源: ${source}`, error);
      // 发生错误时，为了安全起见，跳过上下文分析
      return;
    }
  };

  // 增强的强制分析函数 - 可以选择是否忽略LSP错误
  const forceAnalyze = async (uri: vscode.Uri, position: vscode.Position, ignoreErrors: boolean = false) => {
    const document = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === uri.toString());
    if (!document || !languageManager.isSupported(document.languageId)) {
      return;
    }

    if (!ignoreErrors) {
      try {
        const errorCheck = await LSPErrorChecker.checkLSPErrors(uri);
        if (errorCheck.hasErrors) {
          console.log(`强制分析被阻止: 文件存在LSP问题 (${errorCheck.details.summary})`);
          vscode.window.showWarningMessage(
            `无法分析: 文件存在 ${errorCheck.details.summary}，请先修复错误`,
            '查看问题',
            '强制分析'
          ).then(selection => {
            if (selection === '查看问题') {
              vscode.commands.executeCommand('workbench.actions.view.problems');
            } else if (selection === '强制分析') {
              // 用户选择强制分析，忽略错误
              forceAnalyze(uri, position, true);
            }
          });
          return;
        }
      } catch (error) {
        console.error('强制分析时LSP检查失败', error);
        vscode.window.showErrorMessage('LSP状态检查失败，无法执行分析');
        return;
      }
    }

    console.log(`执行强制分析 - 忽略错误: ${ignoreErrors}`);
    await errorAnalyzer.smartAnalyze(uri, position);
  };

  // 监听文档打开事件
  const documentOpenListener = vscode.workspace.onDidOpenTextDocument(async (document) => {
    if (!languageManager.isSupported(document.languageId)) {
      return;
    }

    console.log(`文档打开: ${document.fileName}`);
    
    // 文档打开时使用较长的延迟，避免过于频繁
    debouncer.debounce(document.uri, new vscode.Position(0, 0), async () => {
      const activeEditor = vscode.window.activeTextEditor;
      if (activeEditor && activeEditor.document.uri.toString() === document.uri.toString()) {
        const position = activeEditor.selection.active;
        await analyzeIfNoErrors(document.uri, position, '文档打开');
      }
    }, 2000);
  });

  // 监听活动编辑器变化
  const activeEditorChangeListener = vscode.window.onDidChangeActiveTextEditor(async (editor) => {
    if (!editor || !languageManager.isSupported(editor.document.languageId)) {
      return;
    }

    console.log(`编辑器切换: ${editor.document.fileName}, 位置: ${editor.selection.active.line}:${editor.selection.active.character}`);
    
    const position = editor.selection.active;
    // 编辑器切换时使用中等延迟
    debouncer.debounce(editor.document.uri, position, async () => {
      await analyzeIfNoErrors(editor.document.uri, position, '编辑器切换');
    }, 1000);
  });

  // 监听光标位置变化
  const selectionChangeListener = vscode.window.onDidChangeTextEditorSelection(async (event) => {
    const editor = event.textEditor;
    if (!editor || !languageManager.isSupported(editor.document.languageId)) {
      return;
    }

    const position = event.selections[0].active;
    console.log(`光标移动: ${editor.document.fileName}, 位置: ${position.line}:${position.character}`);
    
    // 光标移动时使用较短的延迟，提高响应性
    debouncer.debounce(editor.document.uri, position, async () => {
      await analyzeIfNoErrors(editor.document.uri, position, '光标移动');
    }, 800);
  });

  // 监听 LSP 诊断变化 - 重要：当错误清除时重新启用上下文分析
  const diagnosticsListener = vscode.languages.onDidChangeDiagnostics(async (event) => {
    for (const uri of event.uris) {
      try {
        const errorCheck = await LSPErrorChecker.checkLSPErrors(uri);
        
        if (!errorCheck.hasErrors) {
          console.log(`✅ LSP问题已清除: ${uri.toString()}, 重新启用上下文分析`);
          const activeEditor = vscode.window.activeTextEditor;
          if (activeEditor && activeEditor.document.uri.toString() === uri.toString()) {
            const position = activeEditor.selection.active;
            // 错误清除时快速分析
            debouncer.debounce(uri, position, async () => {
              await analyzeIfNoErrors(uri, position, 'LSP问题清除');
            }, 300);
          }
        } else {
          // 有新的LSP错误时，进行错误分析
          console.log(`❌ 检测到LSP问题: ${uri.toString()} (${errorCheck.details.summary})`);
          await errorAnalyzer.analyzeDiagnostics(event);
        }
      } catch (error) {
        console.error('处理LSP诊断变化时出错', error);
      }
    }
  });

  // 监听文档关闭事件，清理缓存
  const documentCloseListener = vscode.workspace.onDidCloseTextDocument((document) => {
    console.log(`文档关闭，清理缓存: ${document.fileName}`);
    debouncer.clearFileCache(document.uri);
  });

  // 手动触发命令 - 智能分析（检查错误）
  const smartAnalyzeCommand = vscode.commands.registerCommand('extension.smartAnalyze', async () => {
    const activeEditor = vscode.window.activeTextEditor;
    if (!activeEditor) {
      vscode.window.showInformationMessage('请先打开一个文件');
      return;
    }
    
    console.log('手动触发智能分析');
    // 手动触发时不使用防抖，但要检查错误
    debouncer.forceAnalyze(activeEditor.document.uri, activeEditor.selection.active, async () => {
      await forceAnalyze(activeEditor.document.uri, activeEditor.selection.active, false);
    });
  });

  // 强制分析命令（忽略LSP错误）
  const forceAnalyzeIgnoreErrorsCommand = vscode.commands.registerCommand('extension.forceAnalyzeIgnoreErrors', async () => {
    const activeEditor = vscode.window.activeTextEditor;
    if (!activeEditor) {
      vscode.window.showInformationMessage('请先打开一个文件');
      return;
    }
    
    console.log('强制分析（忽略LSP错误）');
    debouncer.forceAnalyze(activeEditor.document.uri, activeEditor.selection.active, async () => {
      await forceAnalyze(activeEditor.document.uri, activeEditor.selection.active, true);
    });
  });

  // 显示详细LSP状态命令
  const showDetailedLSPStatusCommand = vscode.commands.registerCommand('extension.showDetailedLSPStatus', async () => {
    const activeEditor = vscode.window.activeTextEditor;
    if (!activeEditor) {
      vscode.window.showInformationMessage('请先打开一个文件');
      return;
    }
    
    try {
      const errorCheck = await LSPErrorChecker.checkLSPErrors(activeEditor.document.uri);
      const nearbyCheck = await LSPErrorChecker.checkErrorsNearPosition(
        activeEditor.document.uri, 
        activeEditor.selection.active, 
        3
      );
      
      const statusLines = [
        `📁 文件: ${activeEditor.document.fileName}`,
        `📍 当前位置: 第${activeEditor.selection.active.line + 1}行, 第${activeEditor.selection.active.character + 1}列`,
        `🔍 LSP状态: ${errorCheck.details.summary}`,
        `📍 当前位置附近: ${nearbyCheck.hasNearbyErrors ? `有${nearbyCheck.nearbyErrors.length}个问题 (行号: ${nearbyCheck.affectedLines.join(', ')})` : '无问题'}`,
        `⚡ 上下文分析: ${!errorCheck.hasErrors && !nearbyCheck.hasNearbyErrors ? '✅ 可执行' : '❌ 已暂停'}`
      ];
      
      const statusMessage = statusLines.join('\n');
      vscode.window.showInformationMessage(statusMessage, { modal: true });
      console.log('详细LSP状态:\n' + statusMessage);
      
    } catch (error) {
      vscode.window.showErrorMessage('获取LSP状态失败');
      console.error('获取LSP状态失败', error);
    }
  });

  // 清理分析缓存命令
  const clearCacheCommand = vscode.commands.registerCommand('extension.clearAnalysisCache', () => {
    debouncer.clear();
    vscode.window.showInformationMessage('分析缓存已清理');
    console.log('分析缓存已手动清理');
  });

  // 显示分析统计命令
  const showStatsCommand = vscode.commands.registerCommand('extension.showAnalysisStats', () => {
    const stats = debouncer.getStats();
    const message = `分析统计: ${stats.totalPositions} 个位置已缓存, ${stats.activeTimeouts} 个待处理任务`;
    vscode.window.showInformationMessage(message);
    console.log(message);
  });

  context.subscriptions.push(
    documentOpenListener,
    activeEditorChangeListener,
    selectionChangeListener,
    diagnosticsListener,
    documentCloseListener,
    smartAnalyzeCommand,
    forceAnalyzeIgnoreErrorsCommand,
    showDetailedLSPStatusCommand,        // 增强的LSP状态显示
    clearCacheCommand,
    showStatsCommand
  );

  console.log('LSP 错误分析和上下文分析扩展已激活');
  
  // 定期清理过期的缓存和状态检查
  const cleanupInterval = setInterval(async () => {
    console.log('定期缓存清理检查');
    
    // 输出当前所有打开文档的LSP状态统计
    const openDocuments = vscode.workspace.textDocuments;
    let totalErrors = 0;
    let documentsWithErrors = 0;
    
    for (const document of openDocuments) {
      if (languageManager.isSupported(document.languageId)) {
        try {
          const errorCheck = await LSPErrorChecker.checkLSPErrors(document.uri);
          if (errorCheck.hasErrors) {
            totalErrors += errorCheck.details.count;
            documentsWithErrors++;
          }
        } catch (error) {
          // 忽略检查错误
        }
      }
    }
    
    if (documentsWithErrors > 0) {
      console.log(`LSP状态汇总: ${documentsWithErrors}个文件存在问题，总计${totalErrors}个问题`);
    } else {
      console.log('LSP状态汇总: 所有文件无问题');
    }
  }, 5 * 60 * 1000); // 每5分钟检查一次

  context.subscriptions.push({
    dispose: () => clearInterval(cleanupInterval)
  });
}

export function deactivate() {
  // 清理所有定时器
  if ((global as any).contextAnalyzeTimeout) {
    clearTimeout((global as any).contextAnalyzeTimeout);
  }
  console.log('上下文分析扩展已停用');
}